package com.atguli.gulimall.product.service.impl;

import com.atguli.common.entity.QueryWrapperVO;
import com.atguli.common.enums.BizCodeEnum;
import com.atguli.common.exception.RRException;
import com.atguli.gulimall.product.service.CategoryBrandRelationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguli.common.utils.PageUtils;
import com.atguli.common.utils.Query;

import com.atguli.gulimall.product.dao.BrandDao;
import com.atguli.gulimall.product.entity.BrandEntity;
import com.atguli.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("brandService")
@Slf4j
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Resource
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(QueryWrapperVO params) {
        log.info("进入查询");
        final QueryWrapper<BrandEntity> condition = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(params.getKey())) {
            log.info("带关键字查询");
            condition.like("name",params.getKey()).or()
                    .eq("brand_id",params.getKey());
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                condition
        );
        log.info("查询结束");
        return new PageUtils(page);
    }

    /**
     * 多表更新
     *
     * @param brand
     */
    @Override
    @Transactional(rollbackFor = RRException.class)
    public void updateDetail(BrandEntity brand) {
        if (StringUtils.isNotEmpty(brand.getName())) {
            log.info("同步更新其他关联表");
            try {
                categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());
                // TODO 更新其他关联表
            } catch (RuntimeException e) {
                log.error(e.getLocalizedMessage());
                throw new RRException(BizCodeEnum.TRANSACTIONAL_EXCEPTION.getMessage(),BizCodeEnum.TRANSACTIONAL_EXCEPTION.getCode());
            }
        }
        this.updateById(brand);
    }

}